interface ICallback {
  (...args: any[]): void
}

export default class EventEmitter {
  // 用于保存注册的各事件监听的回调
  private listeners: Record<string, Array<ICallback>> = {}
  // listeners.click = [ ()=>{}, ()=>{} ]
  // listeners.keydown = [ ()=>{} ]

  /**
   * 注册事件的监听(绑定事件)
   * addEventListener
   */
  on(type: string, callback: ICallback) {
    // 查找是否已有之前的绑定
    const has = this.listeners[type]
    // 如果有，则直接继续添加绑定的事件函数，
    // 如果没有，则向 listeners 对象中新增一项事件绑定属性
    if (has) {
      has.push(callback)
    } else {
      this.listeners[type] = [ callback ]
    }
  }

  /**
   * 移除事件监听
   * removeEventListener
   */
  off(type: string, callback?: ICallback) {
    const has = this.listeners[type]
    if (has) {
      if (callback) {
        this.listeners[type] = has.filter(cb => cb !== callback)
      } else {
        this.listeners[type] = []
      }
    }
  }

  /**
   * 触发事件
   */
  emit(type: string, ...args: any[]) {
    const has = this.listeners[type]
    if (has) {
      has.forEach(cb => cb(...args))
    }
  }
}